<template>
  <div class="chat-container">
    <el-card class="chat-box">
      <div ref="messages" class="message-area">
        <div v-for="(msg, index) in messages" :key="index">
          <div :class="['message', msg.role]">
            {{ msg.content }}
          </div>
        </div>
      </div>
      <el-input 
        v-model="inputMessage"
        placeholder="输入问题..."
        @keyup.enter.native="sendMessage"
      >
        <template #append>
          <el-button @click="sendMessage">发送</el-button>
        </template>
      </el-input>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import axios from '@/utils/request'

const messages = ref([])
const inputMessage = ref('')

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return
  
  const prompt = inputMessage.value
  messages.value.push({ role: 'user', content: prompt })
  inputMessage.value = ''
  
  try {
    const response = await axios.post('/api/ai/chat', { prompt }, {
      responseType: 'stream'
    })
    
    const reader = response.body.getReader()
    let aiMessage = { role: 'ai', content: '' }
    
    const processChunk = async ({ done, value }) => {
      if (done) return
      const chunk = new TextDecoder().decode(value)
      aiMessage.content += chunk
      messages.value = [...messages.value]
      await nextTick()
      reader.read().then(processChunk)
    }
    
    reader.read().then(processChunk)
    
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
}
</script>
